<template>
  <span v-loading="loading" class=" ">
    <!-- <el-button type="success" plain :icon="CircleCheckFilled" @click="sendAdminSet('open_container')">开通</el-button> -->
    <el-button
      type="primary"
      plain
      :icon="CreditCard"
      @click="update_container_renew()"
      >续费</el-button
    >
    <el-button
      type="success"
      plain
      :icon="CircleCheck"
      @click="sendSet('start')"
      >开机</el-button
    >
    <el-button type="info" plain :icon="SwitchButton" @click="sendSet('stop')"
      >关机</el-button
    >
    <el-button type="warning" plain :icon="Refresh" @click="sendSet('reboot')"
      >重启</el-button
    >
    <el-button type="warning" plain :icon="Refresh" @click="toRein"
      >重装</el-button
    >
    <el-button type="danger" plain :icon="Delete" @click="back_dialog = true"
      >退款</el-button
    >
    <el-button @click="sendSet('console')"> 控制台 </el-button>
    <el-button @click="file()"> 文件管理 </el-button>
    <FileManage ref="childRef" />
  </span>
  <el-dialog v-model="continueC" title="续费">
    <el-form :model="paylist" label-width="100px">
      <el-form-item label="续费时长/月">
        <el-input
          v-model="paylist.pay_months"
          type="number"
          min="0"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="支付方式">
        <el-checkbox label="优先使用余额支付" checked disabled />
        <el-radio v-model="paylist.pay_type" :value="0" size="large"
          >支付宝
        </el-radio>
        <el-radio v-model="paylist.pay_type" :value="1" size="large"
          >微信</el-radio
        >
      </el-form-item>
      <el-form-item v-if="pay_src != ''" label="扫码支付">
        <el-image style="width: 100px; height: 100px" :src="pay_src" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="pay_money">
        <el-statistic
          title="总计结算金额："
          :value="payprice != 0 ? payprice + '元' : '- -' + ' 元'"
          suffix=""
        >
          <template #suffix>
            <el-icon style="vertical-align: -20px">
              <ChatLineRound />
            </el-icon>
          </template>
        </el-statistic>
      </div>
      <div class="dialog-footer">
        <el-button @click="continueC = false">关闭</el-button>
        <el-button
          type="primary"
          :disabled="payprice == 0 ? true : false"
          @click="topay"
          >提交订单
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog
    v-model="pay_dialog"
    title="支付"
    style="width: 90%; height: 1000px"
  >
    <iframe
      :srcdoc="pay_url"
      frameborder="0"
      style="width: 100%; height: 800px"
    />
  </el-dialog>
  <el-dialog v-model="back_dialog" title="退款" width="40%">
    <el-form v-loading="loading">
      <el-form-item label="请先输入账号密码">
        <el-input v-model="pay_password" type="password" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="back_dialog = false">关闭</el-button>
        <el-button type="primary" @click="toback">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="image_dialog" title="重装" width="40%">
    <el-form v-loading="loading">
      <el-form-item label="镜像">
        <el-select v-model="image_id" placeholder="你可以选择重装镜像">
          <el-option
            v-for="item in image_list"
            :key="item.value"
            :label="item.show_name ? item.show_name : item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="image_dialog = false">关闭</el-button>
        <el-button type="primary" @click="torein">确认重装</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  Refresh,
  SwitchButton,
  CircleCheck,
  Delete,
  CreditCard,
  CircleCheckFilled
} from "@element-plus/icons-vue";
import {
  startUserContainer,
  startAdminContainer,
  getContainerDetail,
  pay_request,
  procedureUpdateContainerRenew,
  backUserContainer,
  reinContainer
} from "@/api";
import { getUserMirrorList } from "@/api/mirror";
import {
  ref,
  getCurrentInstance,
  defineEmits,
  reactive,
  watch,
  onMounted
} from "vue";
import { message } from "@/utils/message";
import { useRouter } from "vue-router";
import FileManage from "@/views/self/components/FileManage.vue";
import { ElLoading } from "element-plus";
const router = useRouter();
const emits = defineEmits(["statusUpdated"]);

const props = defineProps({
  id: [String, Number],
  console_url: [String],
  server_id: [String],
  trade_type: [String]
});

const loading = ref(false);
const childRef = ref();

const continueC = ref(false);
const pay_src = ref("");
const pay_url = ref("");
const pay_dialog = ref(false);

const paylist = reactive({
  pay_type: "",
  pay_months: "",
  container_id: "",
  trade_type: ""
});
const back_dialog = ref(false);
const pay_password = ref("");

const payprice = ref(0);
const oneprice = ref("");
const getoneprice = async () => {
  let res = await getContainerDetail(props.id);
  console.log("获取价格", res.data.data.plan.price);
  oneprice.value = res.data.data.pay;
};
watch(
  [paylist],
  () => {
    getprice();
  },
  { deep: true }
);
const getprice = () => {
  payprice.value = oneprice.value * paylist.pay_months;
};
//获取容器价格

// 文件管理
const file = () => {
  childRef.value.outer();
};

// 启动容器
function sendSet(type = "start") {
  loading.value = true;
  if (type === "console") {
    startUserContainer(type, props.id).then(res => {
      let token = res.data.data.data.token;
      let serevr_addr = props.console_url;
      router.push(`/self/console?token=${token}&serevr_addr=${serevr_addr}`);
    });
  }
  startUserContainer(type, props.id)
    .then(res => {
      console.log("成功1111111111111");
      if (res.data.code === 200) {
        message("操作成功", {
          type: "success"
        });
        emits("statusUpdated");
      } else {
        message(res.data.msg, {
          type: "error"
        });
      }
      loading.value = false;
    })
    .catch(e => {
      console.log("失败1111111111111");
      message(e.response.data.description, {
        type: "error"
      });
      loading.value = false;
    });
}
function sendAdminSet(type = "start") {
  // loading.value = true;
  startAdminContainer(type, props.id)
    .then(res => {
      if (res.data.code === 200) {
        message("操作成功", {
          type: "success"
        });
      } else {
        message(res.data.data, {
          type: "success"
        });
      }
      loading.value = false;
    })
    .catch(e => {
      message(e.response.data.description, {
        type: "error"
      });
      loading.value = false;
    });
}
let { proxy } = getCurrentInstance();
function update_container_renew() {
  paylist.container_id = props.id;
  continueC.value = true;
  getoneprice();
}
const topay = () => {
  paylist.trade_type = props.trade_type;
  procedureUpdateContainerRenew(paylist).then(res => {
    console.log("提交订单", res);
    if (res.data.code == 200) {
      //生成订单
      pay_request({
        pay_type: res.data.data.pay_type,
        trade_id: res.data.data.trade_id
      }).then(res => {
        console.log("支付信息", res);
        if (res.data.data.type == "html") {
          pay_url.value = res.data.data.html;
          pay_dialog.value = true;
        } else if (res.data.data.type == "img") {
          pay_src.value = res.data.data.img;
        } else {
          message("支付成功", { type: "success" });
        }
      });
    } else {
      message(res.data.msg, { type: "error" });
    }
  });
};
//退款
const toback = () => {
  if (pay_password.value == "") {
    message("请输入密码", { type: "error" });
  } else {
    loading.value = true;
    backUserContainer({
      container_id: props.id,
      password: pay_password.value
    }).then(res => {
      if (res.data.code == 200) {
        message("退款成功", { type: "success" });
        back_dialog.value = false;
        router.push("/product/product");
      } else {
        message(res.data.msg, { type: "error" });
        loading.value = false;
      }
    });
  }
};
//重装
const image_dialog = ref(false);
const image_list = ref([]);
const image_id = ref();
const toRein = async () => {
  image_dialog.value = true;
  let res = await getUserMirrorList({
    server_id: props.server_id,
    count: 100,
    key: "",
    page: 1
  });
  console.log("获取镜像", res.data.data);
  res = res.data.data;
  image_list.value = res.map(item => {
    return {
      label: item.name,
      value: item.image_id,
      show_name: item.show_name
    };
  });
};
const torein = () => {
  const loading = ElLoading.service({
    lock: true,
    text: "容器重装中..."
  });

  reinContainer({ container_id: props.id, image_id: image_id.value })
    .then(res => {
      if (res.data.code == 200 && res.data.data.data.container_uuid) {
        message("容器重装完成", { type: "success" });
        loading.close();
        router.push(
          `/self/container?container_id=${res.data.data.data.container_uuid}`
        );
      } else {
        message(res.data.msg, { type: "error" });
        loading.close();
      }
    })
    .catch(e => {
      message("重装失败", { type: "error" });
      loading.close();
    });
};
</script>

<style lang="scss" scoped></style>
